package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
)

type DevicePosition struct{}

// PositionNameMap 获取位置名称
func (DevicePosition) PositionNameMap(ctx context.Context, devicePositionIDs []string) map[string]string {
	idNameMap := make(map[string]string)
	dp := dal.DevicePosition
	dpx := dp.WithContext(ctx)
	records, err := dpx.Where(dp.ID.In(devicePositionIDs...)).Find()
	if err != nil {
		return nil
	}
	for _, record := range records {
		idNameMap[record.ID] = record.Name
	}
	return idNameMap
}

// List 楼层位置列表
func (DevicePosition) List(ctx context.Context, floorID string) ([]*models.DevicePosition, error) {
	dp := dal.DevicePosition
	dpx := dp.WithContext(ctx)
	records, err := dpx.Where(dp.FloorID.Eq(floorID)).Find()
	return records, err
}

// Add 新增楼层位置
func (DevicePosition) Add(ctx context.Context, floorID, positionName string) (string, error) {
	f := dal.Floor
	fx := f.WithContext(ctx)
	dp := dal.DevicePosition
	dpx := dp.WithContext(ctx)

	if floorID == "" {
		return "", errorx.New("楼层id不能为空", -1)
	}
	if positionName == "" {
		return "", errorx.New("位置名称不能为空", -1)
	}
	count, _ := fx.Where(f.ID.Eq(floorID)).Count()
	if count <= 0 {
		return "", errorx.New("无效的楼层", -1)
	}
	record := &models.DevicePosition{
		Name:    positionName,
		FloorID: floorID,
	}
	err := dpx.Create(record)
	return record.ID, err
}

// Update 更新楼层位置
func (DevicePosition) Update(ctx context.Context, positionID, positionName string) error {
	dp := dal.DevicePosition
	dpx := dp.WithContext(ctx)
	count, _ := dpx.Where(dp.ID.Eq(positionID)).Count()
	if count <= 0 {
		return errorx.New("无效的位置", -1)
	}
	res, _ := dpx.Where(dp.ID.Eq(positionID)).Update(dp.Name, positionName)
	if res.RowsAffected < 1 {
		return errorx.New("更新失败")
	}
	return nil
}

// Delete 删除楼层位置
func (DevicePosition) Delete(ctx context.Context, positionID string) error {
	d := dal.Device
	dp := dal.DevicePosition
	count, _ := d.WithContext(ctx).Where(d.PositionID.Eq(positionID)).Count()
	if count > 0 {
		return errorx.New("正在被使用，不能删除", -1)
	}
	res, _ := dp.WithContext(ctx).Where(dp.ID.Eq(positionID)).Delete(&models.DevicePosition{})
	if res.RowsAffected <= 0 {
		return errorx.New("删除失败", -1)
	}
	return nil
}
